#include "pch.h"
#include "LoopBuffer.h"
#include "Session.h"

char* LoopBuffer::tryGet(size_t reqsize)
{
	if (_top == _end) {
		_top = _end = _buf;
	}
	char* p = _top;
	size_t capa;
	if ((_top + reqsize) > _eof) {
		p = _buf;
		if (p == _end) return NULL;
	}
	capa = p < _end ? _end - p : _eof - p;
	return capa > reqsize ? p : NULL;
}
PMemoryHead LoopBuffer::realGet(void* handle, char* p, size_t reqsize)
{
	PMemoryHead ph;
	ph = (PMemoryHead)_top;
	if (p != _top) {
		ph = (PMemoryHead)_top;
		ph->cnext = p;
		ph->vhandle = NULL;
		ph->use = 0;
	}
	_top = p + reqsize;
	ph = (PMemoryHead)p;
	ph->cnext = _top;
	ph->vhandle = handle;
	ph->tm = GetTickCount();
	ph->use = 1;
	return ph;
}

VOID LoopBuffer::TimerRoutine(LoopBuffer& pool, BOOLEAN TimerOrWaitFired)
{
	DWORD tm = GetTickCount();
	EnterCriticalSection(&pool.csLock);
	PMemoryHead ph = (PMemoryHead)pool._end;
	if (ph->use && ph->ihandle && pool._end != pool._top && tm - ph->tm > 3000) {
		RELEASE_SOCKET(ph->ihandle->socket);
	}
	LeaveCriticalSection(&pool.csLock);
}